package org.ouwh.fw.schedule;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ouwh.fw.model.data.Struct;
import org.ouwh.fw.model.service.Service;

/**
 * Timer
 * 
 */
public class ScheduleService extends Service {
	private static final String SCHEDULE = "schedule";

	private static final String TASK_CLASS = "task-class";

	private static Log log = LogFactory.getLog(ScheduleService.class);

	private ScheduleThread scheduleThread;

	private String taskClassName;

	private String schedule;

	@Override
	protected void init(Properties props) {
		taskClassName = props.getProperty(TASK_CLASS);
		schedule = props.getProperty(SCHEDULE);
		log.info("ScheduleService[" + getId() + "]initialized.");
	}

	@Override
	protected void startup() throws Exception {
		IScheduleTask task = (IScheduleTask) Class.forName(taskClassName)
				.newInstance();
		scheduleThread = new ScheduleThread();
		scheduleThread.setTask(task);
		scheduleThread.setSchedule(schedule);
		scheduleThread.setName(getId());
		scheduleThread.startup();
		log.info("ScheduleService[" + getId() + "]started.");
	}

	@Override
	protected void reset(Properties props) throws Exception {
		String tmpTaskClass = props.getProperty(TASK_CLASS);
		schedule = props.getProperty(SCHEDULE);
		if (tmpTaskClass.equals(taskClassName)) {
			scheduleThread.setSchedule(schedule);
			log.info("ScheduleService[" + getId()
					+ "]resetted without restart.");
		} else {
			stop();
			start();
			log.info("ScheduleService[" + getId() + "]resetted by restart.");
		}
	}

	protected void shutdown() {
		log.info("ScheduleService[" + getId() + "]stopping...");
		scheduleThread.shutdown();
		log.info("ScheduleService[" + getId() + "]stopped.");
	}

	@Override
	protected void dumpToStruct(Struct struct) {
		struct.addData(TASK_CLASS, taskClassName);
		struct.addData(SCHEDULE, scheduleThread.getSchedule());
		struct.addData("task-info", scheduleThread.getTaskInfo());
	}
}
